package com.dan.controller;

import com.dan.pojo.Article;
import com.dan.pojo.PageBean;
import com.dan.pojo.Result;
import com.dan.service.impl.ArticleServiceImpl;
import com.dan.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author danqihao
 */
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private ArticleServiceImpl articleServiceImpl;

    @GetMapping("/list")
    public Result<PageBean<Article>> list(@RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "10") Integer pageSize
    ) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        
        PageBean<Article> pb = new PageBean<>();
        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articles = articleServiceImpl.list(pageNum, pageSize, userId);
        //Page中提供了方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<Article> p = (Page<Article>) articles;
        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
//        return pb;

        return Result.success(pb);
    }

    @PostMapping("/save")
    public Result save(@RequestBody @Validated Article article) {
     /*   article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());*/
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);

        articleServiceImpl.save(article);
        return Result.success();
    }
}
